package io.kimmking.rpcfx.proxy;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.Filter;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.api.RpcfxResponse;
import io.kimmking.rpcfx.client.NettyClient;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;


/**
 * @author lfy
 */
public class CustomInterceptor implements MethodInterceptor {
    private final Class<?> serviceClass;
    private final String url;
    private final Filter[] filters;

    public CustomInterceptor(Class<?> serviceClass, String url, Filter... filters) {
        this.serviceClass = serviceClass;
        this.url = url;
        this.filters = filters;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

        RpcfxRequest request = new RpcfxRequest();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(args);
        if (null!=filters) {
            for (Filter filter : filters) {
                if (!filter.filter(request)) {
                    return null;
                }
            }
        }
        RpcfxResponse response = post(request, url);
        Class<?> returnType = method.getReturnType();
        return JSON.parseObject(response.getResult().toString(),returnType);
    }



    private RpcfxResponse post(RpcfxRequest req, String url) throws IOException, URISyntaxException, InterruptedException {
        //String reqJson = JSON.toJSONString(req);


        String reqStr = JSON.toJSONString(req);

        System.out.println("req : "+reqStr);

        // 1.可以复用client
        // 2.尝试使用httpclient或者netty client
//            OkHttpClient client = new OkHttpClient();
//            final Request request = new Request.Builder()
//                    .url(url)
//                    .post(RequestBody.create(JSONTYPE, reqJson))
//                    .build();
//            String respJson = client.newCall(request).execute().body().string();
        String respJson = NettyClient.getResponse(url, reqStr);
        System.out.println("resp : "+respJson);
        return JSON.parseObject(respJson,RpcfxResponse.class);
    }
}
